<template>
  <!-- 产量分析 -->
  <BaseMainSlot @richheight="setheigt">
    <template v-slot:content>
      <div class="analysis-list">
        <!-- 操作 -->
        <div class="search-list">
          <!-- 增加-删除-对比操作 -->
          <div class="analy-list-itemone">
            <div class="itemone-one">
              <div class="search-line">
                选择年份：
                <el-date-picker
                  v-model="searchone.selectyear"
                  type="year"
                  format="yyyy"
                  clearable
                  @change="getbatchlisttwo"
                />
              </div>
              <div class="search-line">
                选择批次：
                <el-select
                  v-model="searchone.batchNo"
                  filterable
                  clearable
                  @change="getfacilitylisttwo"
                >
                  <el-option
                    v-for="batchitem in searchone.batchList"
                    :key="batchitem.batchNo"
                    :label="batchitem.batchName"
                    :value="batchitem.batchNo"
                  />
                </el-select>
              </div>
              <div class="search-line">
                选择设施：
                <el-select v-model="searchone.facilityNo" filterable clearable>
                  <el-option
                    v-for="facilityitem in searchone.facilityList"
                    :key="facilityitem.facilityNo"
                    :label="facilityitem.facilityName"
                    :value="facilityitem.facilityNo"
                  />
                </el-select>
              </div>
            </div>
            <div class="itemone-two">
              <div class="linetwo-one" @click="addline()">
                <i class="el-icon-plus"></i>
              </div>
              <div class="linetwo-one" @click="delline()">
                <i class="el-icon-minus"></i>
              </div>
              <div class="linetwo-two" @click="toanalysisdata()"></div>
            </div>
          </div>
          <!-- 动态生成 -->
          <div
            v-for="(item, index) in forlist"
            :key="index"
            class="analy-list-itemone"
          >
            <div class="itemone-one">
              <div class="search-line">
                选择年份：
                <el-date-picker
                  v-model="searchtwolist[index].selectyear"
                  type="year"
                  format="yyyy"
                  clearable
                  @change="getbatchlist($event, index)"
                />
              </div>
              <div class="search-line">
                选择批次：
                <el-select
                  v-model="searchtwolist[index].batchNo"
                  clearable
                  @change="getfacilitylist($event, index)"
                >
                  <el-option
                    v-for="batchitem in searchtwolist[index].batchList"
                    :key="batchitem.batchNo"
                    :label="batchitem.batchName"
                    :value="batchitem.batchNo"
                  />
                </el-select>
              </div>
              <div class="search-line">
                选择设施：
                <el-select v-model="searchtwolist[index].facilityNo" clearable>
                  <el-option
                    v-for="facilityitem in searchtwolist[index].facilityList"
                    :key="facilityitem.facilityNo"
                    :label="facilityitem.facilityName"
                    :value="facilityitem.facilityNo"
                  />
                </el-select>
              </div>
            </div>
            <!-- 占个位置对齐 -->
            <div class="itemone-two"></div>
          </div>
        </div>
        <!-- 切换按钮 -->
        <selectbutton @nowselectbuttonindex="noselecttype" />
        <!-- <div class="unit" :style="`bottom:${heightone - 10}px;`">
          （单位：斤）
        </div> -->
        <!-- echarts -->
        <div ref="zklchart" class="zchart">
          <zhchart
            class="chart"
            v-if="testchartlist.xAxisdata.length > 0"
            ref="testyuy"
            :cdata="testchartlist"
            :nowwidth="newwidth"
            :nowheight="newheight"
            :zhinterval="zhinterval"
          />
          <div v-else>
            <div class="nodata">无数据</div>
          </div>
        </div>
      </div>
    </template>
  </BaseMainSlot>
</template>
<script>
import selectbutton from "@/components/selectbutton/index.vue";
import nowpagereq from "@/api/digital-production/production-statistics/yield-analysis";
import BaseMainSlot from "@/components/BaseMainSlot/baseone.vue";
import { mymixin } from "@/utils/mixin";
import zhchart from "@/components/Echarts/components/linechart/chartone.vue";
import * as echarts from "echarts";

// import { getToken } from '@/utils/auth';
export default {
  name: "YieldAnalysis",
  components: { BaseMainSlot, selectbutton, zhchart },
  mixins: [mymixin],
  data() {
    return {
      zhinterval: 0,
      // 当前选择状态
      noselecttypestau: 0,
      // 对比搜索项1
      searchone: {
        selectyear: "",
        batchList: [],
        facilityList: [],
        facilityNo: "",
        batchNo: "",
      },
      // 对比搜索2
      searchtwolist: [],
      // 循环数组,每次点击加号里面加个1
      forlist: [],
      // ----
      newwidth: "100%",
      newheight: "100%",
      heightone: "",
      testchartlist: {
        xAxisdata: [],
        xData: ["产量（万斤）"],
        seriesData: [
          {
            name: "产量（万斤）",
            type: "bar",
            data: [],
            barMaxWidth: 60,
            itemStyle: {
              normal: {
                borderRadius: [10, 10, 0, 0],
                // barBorderRadius: 5,
                // barBorderRadius: [10, 10, 0, 0],
                color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
                  { offset: 0, color: "#04FA99" },
                  { offset: 1, color: "#3EACE5" },
                ]),
              },
            },
          },
        ],
      },
      testchartlists: {
        xAxisdata: ["产量1", "产量2"],
        xData: ["产量1", "产量2"],
        seriesData: [
          {
            name: "产量（万斤）",
            type: "bar",
            data: [300, 60],
            barMaxWidth: 60,
            itemStyle: {
              normal: {
                borderRadius: [10, 10, 0, 0],
                // barBorderRadius: 5,
                // barBorderRadius: [10, 10, 0, 0],
                color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
                  { offset: 0, color: "#04FA99" },
                  { offset: 1, color: "#3EACE5" },
                ]),
              },
            },
          },
        ],
      },
    };
  },
  watch: {
    noselecttypestau(newvalue) {
      this.toanalysisdata();
    },
  },
  mounted() {
    // 获取节点
    this.getheight();
    // 根据年份选择批次
    this.getbatchlisttwo();
    // 默认展示数据
    this.getlastmessageone();
  },
  methods: {
    // 默认展示chart
    getlastmessageone() {
      let params = [];
      params.push({
        batchNo: this.searchone.batchNo || undefined,
        facilityNo: this.searchone.facilityNo || undefined,
      });
      this.searchtwolist.forEach((item) => {
        params.push({
          batchNo: item.batchNo,
          facilityNo: item.facilityNo,
        });
      });
      nowpagereq.getlastmessage(params).then((res) => {
        if (res.data) {
          let newlist = res.data;
          // console.log(newlist,'默认');
          this.testchartlist = {
            xAxisdata: [...newlist.xAxisdata],
            xData: newlist.xData,
            seriesData: [
              {
                name: "默认数据",
                type: "bar",
                data: newlist.seriesData[0].data,
                barMaxWidth: 80,
                itemStyle: {
                  normal: {
                    label: {
                      show: true,
                      position: "top",
                      // offset:[0,0],
                      offset: [-40, 10],
                      color: "#FFF",
                      lineHeight: 20,
                      verticalAligh: "top",
                      align: "left",
                      borderType: "solid",
                      width: 80,
                      borderColor: "black",
                      borderRadius: 5,
                      backgroundColor: "rgba(50,50,50,0)",
                      padding: [10, 5, 10, 5],
                      rich: {
                        circle: {
                          width: 12,
                          height: 12,
                          borderRadius: 50,
                          backgroundColor: "rgb(22, 225, 176)",
                        },
                      },
                      formatter: function (params) {
                        console.log(params);
                        return `{circle|}批次：默认批次\n{circle|}设施：默认设施\n{circle|}产量：${params.value}`;
                      },
                    },
                    borderRadius: [10, 10, 0, 0],
                    color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
                      { offset: 0, color: "#04FA99" },
                      { offset: 1, color: "#3EACE5" },
                    ]),
                  },
                },
              },
            ],
          };
        }
      });
    },
    // 选择年份
    getbatchlisttwo(e) {
      this.searchone.facilityList = [];
      this.searchone.batchNo = "";
      this.searchone.facilityNo = "";
      const zhdt = new Date(e);
      const y = zhdt.getFullYear();
      let dateparams = {
        startTime: `${y}-01-01`,
        endTime: `${y}-12-30`,
        organizationNo: sessionStorage.organizationNo,
        simpleData: true
      };
      nowpagereq.getbatchlist(dateparams).then((res) => {
        this.searchone.batchList = res.data;
      });
    },
    // for动态选择年份
    getbatchlist(e, nowselectindex) {
      this.searchtwolist[nowselectindex].batchNo = "";
      this.searchtwolist[nowselectindex].facilityNo = "";
      const zhdt = new Date(e);
      const y = zhdt.getFullYear();
      let dateparams = {
        startTime: `${y}-01-01`,
        endTime: `${y}-12-30`,
        simpleData: true
      };
      nowpagereq.getbatchlist(dateparams).then((res) => {
        this.searchtwolist[nowselectindex].batchList = res.data;
      });
    },
    // 选择批次
    getfacilitylisttwo() {
      this.searchone.facilityNo = "";
      nowpagereq.getfacilitylist(this.searchone.batchNo).then((res) => {
        this.searchone.facilityList = res.data;
      });
    },
    // 动态选择批次
    getfacilitylist(nowselectbatchid, nowselectindex) {
      this.searchtwolist[nowselectindex].facilityNo = "";
      nowpagereq.getfacilitylist(nowselectbatchid).then((res) => {
        this.searchtwolist[nowselectindex].facilityList = res.data;
      });
    },
    // 点击数据对比方法
    toanalysisdata() {
      if (!this.searchone.batchNo && !this.searchone.facilityNo) {
        return this.$message.warning({
          message: `请先选择对比数据:请先选择年份，再选择批次，最后选择设施！`,
        });
      }
      let paramsListone = [];
      paramsListone.push({
        batchNo: this.searchone.batchNo || 1,
        facilityNo: this.searchone.facilityNo || 1,
      });
      this.searchtwolist.forEach((item) => {
        paramsListone.push({
          batchNo: item.batchNo,
          facilityNo: item.facilityNo,
        });
      });
      // 获取总产量
      if (this.noselecttypestau === 0) {
        nowpagereq.getYieldTotalList(paramsListone).then((res) => {
          if (res.code === 0) {
            this.$message.warning("暂无数据");
          } else if (res.code === 1) {
            this.chancedata(res.data);
          }
          // 提示
          if (!res.data[res.data.length - 1].partYieldList.length) {
            this.$message.warning("当前批次和设施暂无数据，请重新选择！");
          }
        });
        return;
      }
      // 获取各个月份亩均产量
      nowpagereq.getYieldMuList(paramsListone).then((res) => {
        if (res.code === 0) {
          this.$message.warning("暂无数据");
        } else if (res.code === 1) {
          this.chancedata(res.data);
          console.log(res.data, "亩均产量");
        }
      });
    },
    // 后端数据处理方法
    chancedata(list) {
      let nowlist = JSON.parse(JSON.stringify(list));
      let newlist = [];
      // 处理name
      let facilityNameList = [];
      nowlist.forEach((item) => {
        console.log(item,'it');
        facilityNameList.push({batchName:item.bathName,facilityName:item.facilityName});
      });
      // 获取x轴数据
      let xAxisdata = [];
      // TODO:
      nowlist[0]["partYieldList"].forEach((xitem) => {
        xAxisdata.push(xitem.months + "月");
      });
      // 判断月份是否匹配
      if (nowlist.length > 1) {
        nowlist[nowlist.length - 1].partYieldList.forEach((it) => {
          if (!xAxisdata.includes(it.months + "月")) {
            this.$message.warning("月份不匹配，无法进行对比，请重新选择设施");
            // return
          }
        });
      }
      nowlist.forEach((item, index) => {
        let objitem = {
          name: `${facilityNameList[index].batchName}`,
          type: "bar",
          barMaxWidth: 100,
          itemStyle: {
            normal: {
              label: {
                show: true,
                position: "top",
                offset: [-50, 0],
                color: "#FFF",
                borderType: "solid",
                borderColor: "black",
                borderRadius: 5,
                lineHeight: 15,
                verticalAligh: "top",
                align: "left",
                overflow: "break",
                backgroundColor: "rgba(50,50,50,0)",
                width: 100,
                fontSize: 12,
                // padding: [10, 5, 10, 5],
                rich: {
                  a: {
                    padding: 6,
                    color: 'rgb(22, 225, 176)',
                    fontSize: 0,
                    borderRadius: 50,
                    backgroundColor: "rgb(22, 225, 176)",
                  },
                  b: {
                    color: 'rgb(22, 225, 176)'
                  }
                },
                // TODO:需要修改设施名和批次名字
                formatter: function (params) {
                  let name = facilityNameList[index].facilityName
                  console.log(params, "pp");
                  return `{a|1}批次：${params.seriesName}\n\n{a|1}设施：${name}\n\n{a|1}产量：${params.value}`;
                },
              },
              borderRadius: [10, 10, 0, 0],
              color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
                { offset: 0, color: "#04FA99" },
                { offset: 1, color: "#3EACE5" },
              ]),
            },
          },
          data: [],
        };
        item.partYieldList.forEach((lhitem, lhindex) => {
          if (xAxisdata.indexOf(lhitem.months + "月") != -1) {
            objitem.data[xAxisdata.indexOf(lhitem.months + "月")] =
              lhitem.monthsYield;
          } else {
            objitem.data.push(0);
          }
        });
        newlist.push(objitem);
      });
      newlist.forEach((item, index) => {
        for (let i = 0; i < item.data.length; i++) {
          if (item.data[i] == undefined) {
            item.data[i] = 0;
          }
        }
      });
      this.testchartlist.xAxisdata = xAxisdata;
      this.testchartlist.seriesData = newlist;
    },
    // 获取画布高度
    getheight() {
      const klll = this.$refs.zklchart;
      let heightone = klll.scrollHeight;
      this.newheight = heightone + "px";
      this.heightone = heightone;
      // this.$refs.testyuy.resetsty();
    },
    setheigt(e) {
      this.getheight();
    },
    // 动态添加搜索节点
    addline() {
      this.searchtwolist.push({
        selectyear: "",
        batchList: this.searchone.batchList,
        facilityList: [],
        facilityNo: "",
        batchNo: "",
      });
      this.forlist.push(1);
    },
    // 动态删除搜索节点
    delline() {
      this.searchtwolist.pop();
      this.forlist.pop();
      this.toanalysisdata();
    },
    // 切换0总产量-1亩均产量
    noselecttype(i) {
      this.noselecttypestau = i;
      this.toanalysisdata();
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep {
  .zhcontent {
    overflow: hidden !important;
  }
}
.search-list {
  width: 100%;
  height: 150px;
  overflow: auto;
}
.analysis-list {
  position: relative;
  width: 100%;
  height: 100%;
  // border: rgb(55, 211, 55) solid 1px;
  font-size: 20px;
  // overflow: auto;
  .analy-list-itemone {
    width: 100%;
    display: flex;
    height: 50px;
    flex-direction: row;
    // justify-content: space-between;
    .itemone-one {
      width: 80%;
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      margin: 5px;
      .search-line {
        display: flex;
        white-space: nowrap;
        height: 50px;
        line-height: 50px;
      }
    }
    .itemone-two {
      width: 20%;
      display: flex;
      flex-direction: row;
      align-items: center;
      .linetwo-one {
        cursor: pointer;
        width: 30px;
        height: 30px;
        border: #3ed2d2 1px solid;
        text-align: center;
        line-height: 30px;
        color: #3ed2d2;
        margin-left: 10px;
        margin-right: 2px;
      }
      .linetwo-two {
        cursor: pointer;
        width: 100px;
        height: 50px;
        margin-left: 10px;
        background-image: url("~@/assets/analy.png");
        background-position: center;
        background-repeat: no-repeat;
      }
    }
  }
}
.unit {
  position: absolute;
  left: 250px;
}
.zchart {
  position: relative;
  // background-color: turquoise;
  width: 100%;
  height: calc(100% - 170px);
  // background-color: turquoise;
}
.nodata {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 50%;
  transform: translateX(-50%);
}
</style>
